package com.coolingme.web.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 线程池的配置
 * <code>@Async</code>通过该线程池来执行
 *
 * @author wangyue
 * @date 2021/10/28 16:37
 */
@Configuration
public class AsyncConfig implements AsyncConfigurer {

    private Integer corePoolSize = 4;

    private Integer maximumPoolSize = 6;

    private Long keepAliveTime = 2L;

    private TimeUnit unit = TimeUnit.MINUTES;

    /**
     * 阻塞队列
     */
    private BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(500, true);

    /**
     * 线程工厂
     */
    private ThreadFactory threadFactory = new MyThreadFactory();

    /**
     * 饱和策略，只用调用者所在的线程来执行任务
     */
    private RejectedExecutionHandler handler = new ThreadPoolExecutor.CallerRunsPolicy();

    /**
     * 标注名称后，使用@Async("myTaskExecutor")或@Async()都是使用该线程池
     * 不标注名称，@Async("taskExecutor")
     */
//    @Bean("myTaskExecutor")
    @Override
    public Executor getAsyncExecutor() {
        return new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
    }

    /**
     * 自定义线程工厂
     */
    private class MyThreadFactory implements ThreadFactory {

        // 原子类
        private final AtomicInteger integer = new AtomicInteger(1);

        @Override
        public Thread newThread(Runnable r) {
            // 获取并自增
            return new Thread(r, "MyAsync-Thread-" + integer.getAndIncrement());
        }
    }

}
